<template>
  <div class="spanControl-list" style="width: 100%;margin-left: 0!important;">
    <el-card class="box-card card-head" style="margin: 0px; width: 100%; min-height: 99%">
      <div slot="header" class="clearfix">
        <span>商品信息管理</span>
      </div>
      <div class="alert-container clearfix">
        <el-alert v-for="alert in alerts.successes" :key="alert.title"
                  v-bind:title="alert.title"
                  type="success"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.infos" :key="alert.title"
                  v-bind:title="alert.title"
                  type="info"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.warnings" :key="alert.title"
                  v-bind:title="alert.title"
                  type="warning"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.errors" :key="alert.title"
                  v-bind:title="alert.title"
                  type="error"
                  show-icon>
        </el-alert>
      </div>
      <div class="text item">
        <el-form ref="goodsForm" :model="goods" label-width="150px" :rules="rules">
          <!--<div style="display:inline-block;width: 60px;height: 25px;margin-left: 187px">商品图片</div>-->
          <el-col :span="11">
            <el-form-item label="商品名称" prop="goodsName">
              <file-tip content="商品名称"></file-tip>
              <el-input type="input" v-model="goods.goodsName"
                        placeholder="商品名称" clearable autosize
                        resize="both" tabindex=4
                        maxlength=100
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商品简介" prop="goodsIntroduction">
              <file-tip content="商品简介"></file-tip>
              <el-input type="input" v-model="goods.goodsIntroduction"
                        placeholder="商品简介" clearable autosize
                        resize="both" tabindex=7
                        maxlength=500
              ></el-input>
            </el-form-item>
          </el-col>
          <!--<el-col :span="11">-->
          <!--<el-form-item label="名称" prop="name">-->
          <!--<file-tip content="名称"></file-tip>-->
          <!--<el-input type="input" v-model="goods.name"-->
          <!--placeholder="名称" clearable autosize-->
          <!--resize="both" tabindex=1-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->


          <el-col :span="11">
            <el-form-item label="商品价格" prop="goodsPrice">
              <el-input type="number" step="0.01" v-model="goods.goodsPrice"
                        placeholder="商品价格" clearable autosize
                        resize="both" tabindex=5
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="商品原价" prop="standardPrice">
              <el-input type="number" step="0.01" v-model="goods.standardPrice"
                        placeholder="商品原价" clearable autosize
                        resize="both" tabindex=6
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>


          <el-col :span="11">
            <el-form-item label="商品库存" prop="inventory">
              <el-input type="number" step="1" v-model="goods.inventory"
                        placeholder="商品库存" clearable autosize
                        resize="both" tabindex=9
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商品月售" prop="goodsSale">
              <el-input type="number" step="1" v-model="goods.goodsSale"
                        placeholder="商品月售" clearable autosize
                        resize="both" tabindex=10
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商品状态" prop="goodsStatus">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="goods.goodsStatus"
                :fetch-suggestions="searchGoodsStatus "
                placeholder="商品状态"
                clearable autosize
                resize="both" tabindex="11"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商品类型" prop="goodsTypeName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="goods.goodsTypeName"
                :fetch-suggestions="searchGoodsTypeName "
                placeholder="商品类型"
                @select="handleSelectGoodsTypeName"
                clearable autosize
                resize="both" tabindex="8"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="商家" prop="businessName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="goods.businessName"
                :fetch-suggestions="searchBusinessName "
                placeholder="商家"
                @select="handleSelectBusinessName"
                clearable autosize
                resize="both" tabindex="3"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <!--<el-col :span="22">-->
          <!--<el-form-item label="备注" prop="remark">-->
          <!--<file-tip content="备注"></file-tip>-->
          <!--<el-input type="textarea" v-model="goods.remark"-->
          <!--placeholder="备注" clearable autosize-->
          <!--resize="both" tabindex=10000-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="11">
            <el-form-item>
              <el-button type="primary" @click="submitGoods()" :loading="isSubmiting"
                         v-permission:simple_goods_Goods_Edit>提交
              </el-button>
              <el-button type="primary" @click="backPage" style="background: #CC3300">取消
              </el-button>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="上传图片">
              <el-upload
                class="upload-demo"
                action=""
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="FileChange"
                :file-list="fileLists"
                :auto-upload="false"
                list-type="picture">
                <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="change">确认上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="商品图片">
              <div v-for=" files in fileArray">
              <img height="100px" width="100" style="text-align: center" :src="headerFile+files.attachmentAddr"/>
                <span @click="deleteFile(files.eid)" style="cursor: pointer; color: red">删除图片</span>
              </div>
            </el-form-item>
          </el-col>

        </el-form>
      </div>

      <div class="text item clearfix">
        <el-alert v-for="remark in alerts.remarks" :key="remark.title"
                  v-bind:title="remark.title"
                  type="info"
                  v-bind:description="remark.content">
        </el-alert>
      </div>
    </el-card>


  </div>

</template>

<script>

  import {BusinessService} from '../../simple/businessRegistration/BusinessService'
  import {GoodsTypeService} from '../../simple/goods/GoodsTypeService'
  import {GoodsService} from './GoodsService'
  import {d4utils} from '../../../tools/d4utils'
  import fileTip from '@/components/tip/fileTip'


  export default {
    components: {
      fileTip
    },
    data() {

      var validateIntRange = d4utils.validateFloatRange;
      var validateFloatRange = d4utils.validateFloatRange;
      var validateString = d4utils.validateString;

      return {
        fileLists: [],
        fileArray: [],
        headerFile: process.env.BASE_FILE_VIEW,
        rules: {
          businessId: [
            {required: true, message: '请输入商家', trigger: 'blur'},
          ],
          businessName: [
            {required: false, message: '请输入商家', trigger: 'blur'},
          ],
          goodsName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          goodsPrice: [
            {required: true, message: '请输入商品价格', trigger: 'blur'},
            {validator: validateFloatRange(-9223372036854775808, 9223372036854775807), trigger: 'blur'},
          ],
          standardPrice: [
            {required: true, message: '请输入商品原价', trigger: 'blur'},
            {validator: validateFloatRange(-9223372036854775808, 9223372036854775807), trigger: 'blur'},
          ],
          goodsIntroduction: [
            {required: true, message: '请输入商品简介', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          goodsTypeName: [
            {required: false, message: '请输入商品类型', trigger: 'blur'},
          ],
          goodsTypeId: [
            {required: false, message: '请输入商品类型', trigger: 'blur'},
          ],
          inventory: [

            {required: false, message: '请输入商品库存', trigger: 'blur'},
            {validator: validateIntRange(-9223372036854775808, 9223372036854775807), trigger: 'blur'},
          ],
          goodsSale: [

            {required: false, message: '请输入商品月售', trigger: 'blur'},
            {validator: validateIntRange(-9223372036854775808, 9223372036854775807), trigger: 'blur'},
          ],
          goodsStatus: [
            {required: false, message: '请输入商品状态', trigger: 'blur'},
          ],
          remark: [
            {required: false, message: '请输入备注', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
        },
        isSubmiting: false,
        goods: {},
        goodsId: null,
        pickerOptionsCreateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsUpdateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        alerts: {
          remarks: [{title: "功能说明", content: "TODO: 请在这里加上功能说明"},],
          successes: [], //TODO:[{title:'消息内容'},]
          infos: [],
          warnings: [],
          errors: []
        },
      }


    },

    methods: {
      //返回上一页
      backPage() {
        window.history.go(-1);
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      FileChange(file, fileList) {

        this.fileLists = fileList;
      },
      change() {
        console.log("test:"+this.fileLists)
        debugger
        GoodsService.upLoadFile({name: '11', associateFormId: 1, associateFormName: '111'}, this.fileLists).then(
          res => {
            debugger
            this.findFile();
          }
        )
      },

      findFile() {
        debugger
        GoodsService.downLoadFileByIDandName({id: '1', name: '111'}).then(res => {
          this.fileArray = res.data
          console.log(JSON.stringify(res.data))
        })
      },

      deleteFile(id){
        debugger
        GoodsService.deleteFileById({attachmentId: id}).then(res =>{
          this.findFile();
        })

      },

      view(path) {
        window.open(process.env.BASE_FILE_VIEW + "" + path + '&isOnline=true')
      },
      down(path) {
        window.open(process.env.BASE_FILE_VIEW + "" + path)
      },


      addAlert(message, title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        title = title ? title : message;
        this.alerts[type].unshift({title: title, content: message});
      },
      removeAlert(title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        for (var i = this.alerts[type].length - 1; i >= 0; i--) {
          delete this.alerts[type][i]
        }
      },
      submitGoods() {
        var refs = this.$refs;
        refs['goodsForm'].validate(valid => {
          if (valid) {
            if (this.goods.eid)//编辑商品信息
            {
              this.updateGoods();
            } else//保存商品信息
            {
              this.saveGoods();
            }
          } else {
            return false
          }
        })
      },

      saveGoods()//保存商品信息
      {
        this.goods.name = this.goods.goodsName;
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在保存,请稍后...");
        GoodsService.saveGoods(this.goods).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/goods/goods'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;

          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })
        })
      },
      updateGoods()//编辑商品信息
      {
        this.goods.name = this.goods.goodsName;
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在更新,请稍后...");
        GoodsService.updateGoods(this.goods).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/goods/goods'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;
          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })

        })
      },
      findGoodsForEdit(goodsId)//查找商品信息
      {
        GoodsService.findGoodsForEdit(goodsId).then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '查询商品信息出错'
          })
        })
      },
      createGoods()//创建新的商品信息
      {
        GoodsService.createGoods().then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '创建新的商品信息出错'
          })
        })
      },
      prepareForEdit(goodsEditDto) {
        this.goods = goodsEditDto.goods;

        this.goodsStatusCodeTables = goodsEditDto.goodsStatusCodeTables;
        this.businessBusinesss = goodsEditDto.businessBusinesss
        this.goodsTypeGoodsTypes = goodsEditDto.goodsTypeGoodsTypes
      },
      searchGoodsStatus(queryString, cb) {
        var goodsStatusCodeTables = this.goodsStatusCodeTables;
        var results = queryString ? goodsStatusCodeTables.filter(this.createFilterGoodsStatus(queryString)) : goodsStatusCodeTables;
        cb(results);
      },
      createFilterGoodsStatus(queryString) {
        return (GoodsStatus) => {
          return (GoodsStatus.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },


      searchBusinessName(queryString, cb) {
        var businessBusinesss = this.businessBusinesss;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (businessBusinesss) {
          var results = queryString ? businessBusinesss.filter(this.createFilterBusinessName(queryString)) : businessBusinesss;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findBusinesssWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            BusinessService.findBusinesssWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findBusinesssWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterBusinessName(queryString) {
        return (business) => {
          return (business.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectBusinessName(item) {
        this.goods.businessId = item.eid;
      },

      searchGoodsTypeName(queryString, cb) {
        var goodsTypeGoodsTypes = this.goodsTypeGoodsTypes;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (goodsTypeGoodsTypes) {
          var results = queryString ? goodsTypeGoodsTypes.filter(this.createFilterGoodsTypeName(queryString)) : goodsTypeGoodsTypes;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findGoodsTypesWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            GoodsTypeService.findGoodsTypesWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findGoodsTypesWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterGoodsTypeName(queryString) {
        return (goodsType) => {
          return (goodsType.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectGoodsTypeName(item) {
        this.goods.goodsTypeId = item.eid;
      },
    },
    created() {
      this.goodsId = this.$route.params.goodsId;
      if (this.goodsId)//编辑
      {
        this.findGoodsForEdit(this.goodsId);
        this.findFile();
      } else//新增
      {
        this.createGoods();
      }
    },
  }
</script>
<style scoped lang="scss">
  .avatar-uploader {
    width: 128px;
    height: 128px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }

  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
